package com.example.service;

import com.mySpring.BeanPostProcessor;
import com.mySpring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName UserServiceBeanPostProcessor
 * @Description
 * @Author Yin
 * @Date 2021/4/9 0:23
 * @Version 1.0
 */
@Component
public class UserServiceBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println("初始化前");
        if(beanName.equals("userService")){
            ((UserServiceImpl) bean).setName("我好可爱呀");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");
        if(beanName.equals("userService")){
            return Proxy.newProxyInstance(BeanPostProcessor.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("AOP前");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("AOP后");
                    return invoke;
                }
            });
        }
        return bean;
    }
}
